package com.yaoayao.mall.task.task01;

import com.yaoayao.mall.common.util.AuthContextHolder;
import com.yaoayao.mall.rabbit.constant.MqConst;
import com.yaoayao.mall.rabbit.service.RabbitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
@EnableScheduling //开启定时器 任务
@Slf4j
public class SecKillTask {

    @Autowired
    private RabbitService rabbitService;

    //定时器
    //cron 表达式    例如： 每天半夜 12点执行 下面任务
    //@Scheduled(cron = "0 0 0 * * ?")
    //@Scheduled(cron = "0 0/1 * * * ?")
    @Scheduled(cron = "0/30 * * * * ?")
    public void task0(){
        System.out.println(new Date());

        //发消息 MQ 来监督其它微服务完成  不要手动应答  最终一致性
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_TASK,
                MqConst.ROUTING_TASK_1,"");

        //将秒杀表中数据添加到缓存中  只要当天的


    }

    /**
     * 每天下午18点执行
     */
    //@Scheduled(cron = "0/35 * * * * ?")
    @Scheduled(cron = "0 0 18 * * ?")
    public void task18() {
        log.info("task18");
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        if (null !=requestAttributes){
            HttpServletRequest request = requestAttributes.getRequest();
            if(null != request){
                String userId = AuthContextHolder.getUserId(request);
                rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_TASK, MqConst.ROUTING_TASK_18, userId);
            }
        }
    }
}
